// Admin_createAccount.js
import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import { ethers } from 'ethers';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import $ from 'jquery';
import { Upload, message, Button } from 'antd'; // 引入 antd 组件
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons'; // 引入图标

import AdminABI from '../contract/ABIs/Admin.json';
import UserListABI from '../contract/ABIs/UserList.json';
import UserListAddress from '../contract/ADDRESSes/UserListAddress';
import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js';
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress';
import PointsExchangeAddress from "../contract/ADDRESSes/PointsExchangeAddress.js"
import CourseListAddress from "../contract/ADDRESSes/CourseListAddress.js"
import user3 from '../static/bootstrap/images/user3.png';
import gb from '../static/bootstrap/images/gb.svg';
import us from '../static/bootstrap/images/us.svg';
import AdminNavBar from './nav/AdminNavBar';
import Head from './nav/Head.js';


const Admin = () => {
    const [web3, setWeb3] = useState(null);
    const { address } = useParams();
    const [contractAdmin, setContractAdmin] = useState(null);
    const [contractUserList, setContractUserList] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [students, setStudents] = useState([]);

    const requiredColumns = [
        "realName", "idNumber", "studentIDNumber", "classNumber",
        "educationalLevel", "gradeLevel", "nowPoint", "nowCredit",
        "gender", "phone", "password", "accountAddress"
    ];

    useEffect(() => {
        $("html").css({ fontSize: '16px' });
    }, []);

    useEffect(() => {
        async function init() {
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);

                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setContractAdmin(adminInstance);

                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    setIsAdmin(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);

    const validateColumns = (worksheet) => {
        const firstRow = XLSX.utils.sheet_to_json(worksheet, { header: 1 })[0];
        return requiredColumns.every(col => firstRow.includes(col));
    };

    const handleFileChange = async ({ file, fileList }) => {
        if (file.status !== 'done') return;

        const reader = new FileReader();
        reader.onload = async (event) => {
            try {
                const arrayBuffer = event.target.result;
                const data = new Uint8Array(arrayBuffer);
                const workbook = XLSX.read(data, { type: 'array' });
                const worksheet = workbook.Sheets[workbook.SheetNames[0]];

                if (!validateColumns(worksheet)) {
                    message.error("表格格式不正确，请检查列名是否包含指定字段");
                    return;
                }

                const range = XLSX.utils.decode_range(worksheet['!ref']);
                const numberOfAccounts = range.e.r;

                const accountData = [];

                for (let i = 1; i <= numberOfAccounts; i++) {
                    const wallet = ethers.Wallet.createRandom();
                    const mnemonic = wallet.mnemonic.phrase;
                    const accountAddress = wallet.address;
                    const encryptedJson = await wallet.encrypt("123");

                    const cellAddress = XLSX.utils.encode_cell({ r: i, c: 11 });
                    worksheet[cellAddress] = { t: 's', v: accountAddress };

                    accountData.push({
                        directory: `Account${i}`,
                        address: accountAddress,
                        key: encryptedJson,
                        mnemonic: mnemonic,
                    });
                }

                const updatedWorkbook = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
                const blob = new Blob([updatedWorkbook], { type: 'application/octet-stream' });
                saveAs(blob, 'updated_excel_file.xlsx');

                accountData.forEach(({ directory, address, key, mnemonic }) => {
                    const keyBlob = new Blob([key], { type: 'application/json' });
                    saveAs(keyBlob, `${directory}/${address}.key`);

                    const mnemonicBlob = new Blob([mnemonic], { type: 'text/plain' });
                    saveAs(mnemonicBlob, `${directory}/${address}.mnemonic`);
                });

                message.success("创建成功");
            } catch (error) {
                console.error(error);
                message.error("处理文件失败");
            }
        };
        reader.readAsArrayBuffer(file.originFileObj);
    };

    const handleFileUpload = async ({ file, fileList }) => {
        if (file.status !== 'done') return;

        const reader = new FileReader();
        reader.onload = (event) => {
            const data = event.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];

            if (!validateColumns(worksheet)) {
                message.error("表格格式不正确，请检查列名是否包含指定字段");
                return;
            }

            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            setStudents(jsonData.slice(1));
        };
        reader.readAsBinaryString(file.originFileObj);
    };

    const downloadTemplate = () => {
        const worksheet = XLSX.utils.aoa_to_sheet([requiredColumns]);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Template");
        const blob = new Blob([XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })], { type: 'application/octet-stream' });
        saveAs(blob, 'template.xlsx');
    };

    const CreateUser = async () => {
        if (contractUserList) {
            try {
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                const batchSize = 100;
                const totalStudents = students.length;
                let currentIndex = 0;

                while (currentIndex < totalStudents) {
                    const batchStudents = students.slice(currentIndex, currentIndex + batchSize);
                    const realNamesBatch = batchStudents.map(student => student[0]);
                    const idNumbersBatch = batchStudents.map(student => student[1].toString());
                    const studentIDNumbersBatch = batchStudents.map(student => student[2].toString());
                    const classNumbersBatch = batchStudents.map(student => student[3].toString());
                    const educationalLevelsBatch = batchStudents.map(student => student[4]);
                    const gradeLevelsBatch = batchStudents.map(student => student[5]);
                    const nowPointsBatch = batchStudents.map(student => student[6]);
                    const nowCreditsBatch = batchStudents.map(student => student[7]);
                    const gendersBatch = batchStudents.map(student => student[8]);
                    const phonesBatch = batchStudents.map(student => student[9].toString());
                    const passwordsBatch = batchStudents.map(student => student[10].toString());
                    const accountAddressesBatch = batchStudents.map(student => student[11]);

                    console.log("fromAddress:", fromAddress, "Input:", realNamesBatch, idNumbersBatch, studentIDNumbersBatch, classNumbersBatch, educationalLevelsBatch, gradeLevelsBatch, nowPointsBatch, nowCreditsBatch, gendersBatch, phonesBatch, passwordsBatch, accountAddressesBatch);
                    await contractUserList.methods.createUser(
                        ActivityListAddress,
                        MaterialListAddress,
                        PointsExchangeAddress,
                        CourseListAddress,
                        accountAddressesBatch,
                        batchStudents.map((student, index) => ({
                            realName: realNamesBatch[index],
                            idNumber: idNumbersBatch[index],
                            studentIDNumber: studentIDNumbersBatch[index],
                            classNumber: classNumbersBatch[index],
                            educationalLevel: educationalLevelsBatch[index],
                            gradeLevel: gradeLevelsBatch[index],
                            nowPoint: nowPointsBatch[index],
                            nowCredit: nowCreditsBatch[index],
                            gender: gendersBatch[index],
                            phone: phonesBatch[index],
                            password: passwordsBatch[index]
                        }))
                    ).send({ from: fromAddress });

                    currentIndex += batchSize;
                }
                message.success("添加成功");
            } catch (error) {
                console.error(error);
                message.error("添加失败");
            }
        }
    };

    return (
        <div>
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}
            {isAdmin && (
                <div className="page-wrapper" >
                    <div className="main-container" style={{
                        backgroundColor: '#FFFFFF'
                    }}>
                        <AdminNavBar address={address}></AdminNavBar>

                        <div className="app-container">
                            <Head></Head>

                            <div className="app-body">
                                <div className="container-fluid">
                                    <main className="page hire-me-page">
                                        <section className="portfolio-block hire-me">
                                            <div className="container">
                                                <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                                    data-bs-theme="light"
                                                    style={{ backgroundColor: 'rgba(36, 36, 41, 0.6)' }}
                                                >
                                                    <h1>创建MetaMask钱包</h1>
                                                    <div className="mb-3">
                                                        <div className="mt-3">
                                                            <Button
                                                                type="primary"
                                                                icon={<DownloadOutlined />}
                                                                size="large"
                                                                onClick={downloadTemplate}
                                                            >
                                                                下载模板文件
                                                            </Button>
                                                        </div>
                                                        <Upload.Dragger
                                                            name="file"
                                                            multiple={false}
                                                            accept=".xlsx, .xls"
                                                            customRequest={({ file, onSuccess }) => {
                                                                setTimeout(() => {
                                                                    onSuccess("ok");
                                                                }, 0);
                                                            }}
                                                            onChange={handleFileChange}
                                                        >
                                                            <p className="ant-upload-drag-icon">
                                                                <UploadOutlined />
                                                            </p>
                                                            <p className="ant-upload-text">点击或拖拽文件到此区域进行上传</p>
                                                            <p className="ant-upload-hint">支持单个文件上传</p>
                                                        </Upload.Dragger>
                                                    </div>

                                                    <h1>批量注册用户</h1>
                                                    <div className="mb-3">
                                                        <Upload.Dragger
                                                            name="file"
                                                            multiple={false}
                                                            accept=".xlsx, .xls"
                                                            customRequest={({ file, onSuccess }) => {
                                                                setTimeout(() => {
                                                                    onSuccess("ok");
                                                                }, 0);
                                                            }}
                                                            onChange={handleFileUpload}
                                                        >
                                                            <p className="ant-upload-drag-icon">
                                                                <UploadOutlined />
                                                            </p>
                                                            <p className="ant-upload-text">点击或拖拽文件到此区域进行上传</p>
                                                            <p className="ant-upload-hint">支持单个文件上传</p>
                                                        </Upload.Dragger>

                                                        <div className="mb-3 mt-4">
                                                            <Button type="primary" size="large" block onClick={CreateUser}>
                                                                注册
                                                            </Button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </section>
                                    </main>
                                </div>
                            </div>
                            <div className="app-footer">
                                <span>
                                    © Bootstrap Gallery 2023
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default Admin;
